package com.metrics.graphics;

import static com.metrics.utils.GraphicUtil.*;

import java.awt.Color;
import java.io.*;
import java.util.*;

import org.jfree.chart.*;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.general.AbstractDataset;
import org.jfree.data.time.*;
import org.jfree.data.xy.XYDataset;

import com.database.objects.*;
import com.metrics.extractors.MetricExtractor;
import com.metrics.formatters.TimeFormatter;

public class GraphicLineGenerator extends GraphicGenerator {

	private static final String LEGEND_X = "Time";

	private static final String LEGEND_Y = "Contribution";

	@Override
	public AbstractDataset getData(List<Developer> developers, MetricExtractor extractor, Type type, Status status, String start, String finish, TimeFormatter formatter) {
		TimeSeriesCollection data = new TimeSeriesCollection();
		for (Developer developer : developers) {
			TimeSeries series = new TimeSeries(developer.getName());
			Map<RegularTimePeriod, Double> values = extractor.extractWithDate(developer, type, status, start, finish, formatter);
			for (RegularTimePeriod period : values.keySet()) {
				series.add(period, values.get(period));
			}
			data.addSeries(series);
		}
		return data;
	}

	@Override
	public void graphic(OutputStream out, AbstractDataset data) throws IOException {
		JFreeChart chart = ChartFactory.createTimeSeriesChart("", LEGEND_X, LEGEND_Y, (XYDataset) data, true, true, false);
		decorateLineChart(chart);
		ChartUtilities.writeChartAsPNG(out, chart, WIDTH, HEIGHT);
	}

	private void decorateLineChart(JFreeChart chart) {
		XYPlot plot = chart.getXYPlot();
		plot.setBackgroundPaint(Color.WHITE);
		plot.setRangeGridlinePaint(Color.BLACK);
	}

}